package h_10_26;

import java.util.HashMap;

/**
 * 904. 水果成篮
 * https://leetcode.cn/problems/fruit-into-baskets/description/
 */
public class Main2 {
    public int totalFruit(int[] fruits) {
        HashMap<Integer,Integer> map = new HashMap<>();
        int n = fruits.length;
        int left = 0;
        int right = 0;
        int ret = 0;
        int find = 0;
        while(right < n) {
            // 入
            int in = fruits[right];
            map.put(in,map.getOrDefault(in,0) + 1);
            if(map.get(in) == 1) {
                find++;
            }

            // 出
            while(find > 2) {
                int out = fruits[left];
                map.put(out,map.get(out) - 1);
                if(map.get(out) == 0) {
                    find--;
                }
                left++;
            }

            // 更
            ret = Math.max(ret,right - left + 1);
            right++;
        }
        return ret;
    }
}
